<template>
  <div class="params">
    <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" />
    <el-form class="top">
      <el-form-item label="选择商品分类:">
        <el-cascader v-model="value" :props="prop" :options="options" @change="handleChange" />
      </el-form-item>
    </el-form>
    <el-tabs v-model="Tab" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="动态参数" name="first">
        <el-button :disabled="flag" type="primary" @click="addForm[0].show = true">添加参数</el-button>
        <Table :data="paramsData" :cols="cols" row-key="attr_id" :expand-row-keys="expands" @row-click="clickRowHandle" >
          <template #expand="{row}">
              <el-tag
                    v-for="(item,index) in row.attr_vals"
                    :key="index"
                    class="mx-1"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(row,index)"
                >
                    {{ item }}
                </el-tag>
                <el-input
                    v-if="row.inputVisible"
                    ref="InputRef"
                    v-model="row.inputValue"
                    class="ml-1 w-20 width"
                    size="small"
                    @keyup.enter="handleInputConfirm(row)"
                    @blur="handleInputConfirm(row)"
                />
  <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
    + New Tag
  </el-button>
          </template>
          <template #action="{row}">
            <span class="dialog-footer">
              <el-button :icon="Edit" @click="open(row)">编辑</el-button>
              <el-button :icon="Delete" type="danger" @click="del(row)">删除</el-button>
            </span>
          </template>
        </Table>
      </el-tab-pane>
      <el-tab-pane label="静态属性" name="second">
        <el-button :disabled="flag" type="primary" @click="addForm[0].show = true">添加属性</el-button>
        <Table  :data="paramsData" :cols="cols2" row-key="attr_id" :expand-row-keys="expands" @row-click="clickRowHandle">
            <template #expand="{row}">
              <el-tag
                    v-for="(item,index) in row.attr_vals"
                    :key="index"
                    class="mx-1"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(row,index)"
                >
                    {{ item }}
                </el-tag>
                <el-input
                    v-if="row.inputVisible"
                    ref="InputRef"
                    v-model="row.inputValue"
                    class="ml-1 w-20 width"
                    size="small"
                    @keyup.enter="handleInputConfirm(row)"
                    @blur="handleInputConfirm(row)"
                />
  <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(row)">
    + New Tag
  </el-button>
          </template>
          <template #action="{row}">
            <span class="dialog-footer">
              <el-button :icon="Edit" @click="open(row)">编辑</el-button>
              <el-button :icon="Delete" type="danger" @click="del(row)">删除</el-button>
            </span>
          </template>
        </Table>
      </el-tab-pane>
    </el-tabs>
    <!-- 添加 -->
    <Dialog :dialog="addForm">
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addForm[0].show = false">取消</el-button>
          <el-button type="primary" @click="add()">确定</el-button>
        </span>
      </template>
    </Dialog>
    <!-- 修改 -->
    <Dialog :dialog="changeForm">
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="changeForm[0].show = false">取消</el-button>
          <el-button type="primary" @click="changed()">确定</el-button>
        </span>
      </template>
    </Dialog>
  </div>
</template>
<script setup>
import Table from "@/components/Table.vue";
import Dialog from "@/components/Dialog.vue";
import { ref, onMounted } from "vue";
import { getCate } from "@/utils/categories.js";
import { getParams,addParams, delParams, changeParams } from "@/utils/params.js";
import { ElMessage, ElMessageBox } from "element-plus";

// 添加弹框
const addForm = ref([
  {
    show: ref(false),
    title: "添加参数",
    data: ref([
      {
        name: "参数名称:",
        prop: "attr_name",
        value: ""
      },
      {
        prop: "attr_id",
        value: "",
        hide: true
      },
      {
        prop: "attr_sel",
        value: "",
        hide: true
      },
      {
        prop: "attr_vals",
        value: "",
        hide: true
      }
    ])
  },
  {
    slot: "footer"
  }
]);
// 修改弹框
const changeForm = ref([
  {
    show: ref(false),
    title: "修改参数",
    data: ref([
      {
        name: "参数名称:",
        prop: "attr_name",
        value: ""
      },
      {
        prop: "attr_id",
        value: "",
        hide: true
      },
      {
        prop: "attr_sel",
        value: "",
        hide: true
      },
      {
        prop: "attr_vals",
        value: "",
        hide: true
      }
    ])
  },
  {
    slot: "footer"
  }
]);
// 值
const value = ref([]);
// tag_value
const inputValue = ref('');
// tag_visible
const inputVisible = ref(false);
// prop
const prop = { label: "cat_name", value: "cat_id" };
// 商品分类
const options = ref([]);
// 开关
const flag = ref(true);
// 列
const cols = [
     {
        slot:'expand',
        type:'expand',
        title:'',
        align:'center'
    },
  {
    type: "index",
    title: "#",
    width: 60,
    align: "center"
  },
  {
    title: "参数名称",
    name: "attr_name",
    align: "center"
  },
  {
    title: "操作",
    slot: "action",
    align: "center"
  }
];
// 列2
const cols2 = [
     {
        slot:'expand',
        type:'expand',
        title:'',
        align:'center'
    },
  {
    type: "index",
    title: "#",
    width: 60,
    align: "center"
  },
  {
    title: "属性名称",
    name: "attr_name",
    align: "center"
  },
  {
    title: "操作",
    slot: "action",
    align: "center"
  }
];
// 控制展开行
const expands = ref([]);
// 标签栏
const Tab = ref("first");
// 商品分类
const getRigths = async () => {
  var type = 3;
  let data = await getCate(type);
  options.value = data.data;
};
// 表格
const paramsData = ref([]);
// 展开行
const clickRowHandle = (row, column, event)=>{
    console.log(row, column, event)
    if (expands.value.includes(row.attr_id)) {
        expands.value = expands.value.filter(val => val !== row.attr_id);
    } else {
        expands.value.push(row.attr_id);
    }
}
// 参数列表
const getParamsList = async () => {
  var arr = value.value[2];
  var sel = "";
  if (Tab.value == "first") {
    sel = "many";
  } else {
    sel = "only";
  }
  var data = await getParams(arr, sel);
  // console.log(arr,data)
  if (data.meta.status == 200) {
    flag.value = false;
    data.data.map(item=>{
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : [];
        item.inputVisible = false;
        item.inputValue = '';
    })
    paramsData.value = data.data;

  } else {
    flag.value = true;
  }
};
// 添加
const add = async ()=>{
    var form = {};
    addForm.value[0].data.map(item=>{
        return form[item.prop] = item.value
    })
    if(Tab.value == 'first'){
        form.attr_sel = 'many'
    }else{
        form.attr_sel = 'only'
    }
    console.log(form)
    var data = await addParams(value.value[2],form);
    if(data.meta.status == 201){
        ElMessage.success(data.meta.msg);
        addForm.value[0].show = false;
        addForm.value[0].data[0].value = ''
    }
    getParamsList();
}
// 删除
const del = async row => {
  ElMessageBox.confirm(
    `您确认删除【${row.attr_name}】吗？删除后无法恢复`,
    "删除",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(async () => {
      var data = await delParams(value.value[2], row.attr_id);
      ElMessage({
        type: "success",
        message: data.meta.msg
      });
      getParamsList();
    })
    .catch(() => {});
};
// 打开修改弹框
const open = row => {
  changeForm.value[0].show = true;
  changeForm.value[0].data[0].value = row.attr_name;
  changeForm.value[0].data[1].value = row.attr_id;
  changeForm.value[0].data[2].value = row.attr_sel;
  changeForm.value[0].data[3].value = row.attr_vals;
  console.log(row);
};
// 修改
const changed = async () => {
  var form = {};
  changeForm.value[0].data.map(item => {
    return (form[item.prop] = item.value);
  });
  console.log(form, 885);
  let data = await changeParams(value.value[2], form.attr_id, form);
  // console.log(data,'修改')
  if (data.meta.status == 200) {
    ElMessage.success(data.meta.msg);
    changeForm.value[0].show = false;
    getParamsList();
  }
};
// 切换商品分类
const handleChange = val => {
  getParamsList();
};
// 打开输入框tag
const showInput = (row) => {
    row.inputVisible = true;
}
// 删除tag
const handleClose = (row,index) => {
   console.log(row.attr_vals)
  ElMessageBox.confirm(
    `您确认删除这条详情吗？删除后无法恢复`,
    "删除",
    {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning"
    }
  ).then(async () => {
        row.attr_vals.splice(index, 1)
        var obj = JSON.parse(JSON.stringify(row));
        obj.attr_vals = obj.attr_vals.join(',');
        console.log(obj)
        let data = await changeParams(value.value[2],row.attr_id,obj);
      ElMessage({
        type: "success",
        message: '删除成功'
      });
      getParamsList();
    }).catch(() => {});
}
// 添加tag
const handleInputConfirm = async (row) => {
    var str = row.inputValue;
    if (row.inputValue != ""){
        row.attr_vals.push(str);
    }
    var obj = JSON.parse(JSON.stringify(row));
    obj.attr_vals = obj.attr_vals.join(',');
    console.log(obj)
    let data = await changeParams(value.value[2],row.attr_id,obj);
    if (data.meta.status == 200) {
        ElMessage.success(data.meta.msg);
        row.inputVisible = false
        row.inputValue = ''
    }
}
onMounted(() => {
  getRigths();
});
</script>
<style lang="scss" scoped>
.demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}
.top {
  margin: 20px 0;
}
.width{
    width: 100px;
}
</style>